package fr.esisar.picaso.moteur;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import fr.esisar.picaso.entites.ClientAuthentifie;
import fr.esisar.picaso.ihm.FenetreAccueil;
import fr.esisar.picaso.requetes.RequetesAdresse;


public class Connexion {

	private static Connection instance;
	private static String ipServeur;

	private Connexion() {

	}

	public static Connection getConnection() throws SQLException{
		if (instance == null)
			try {
				//A remettre à 127.0.0.1 avant d'envoyer au prof
				ipServeur = "127.0.0.1";
				Class.forName("oracle.jdbc.driver.OracleDriver");

				Crypteur crypteur = new Crypteur();
				
				Connection connexion = Connexion.getAdminConnection();
				Statement st = connexion.createStatement();

				String requete = "SELECT * FROM u0.clientAuthentifie WHERE email LIKE '" + FenetreAccueil.getInstance().getLogin() + "'";

				ResultSet rs = st.executeQuery(requete);
			
				rs.next();
				int idClient = rs.getInt("idClient");
				
				Connexion.terminerConnexion();
				
				instance = DriverManager.getConnection("jdbc:oracle:thin:@//" + ipServeur + ":1521/xe",
						   crypteur.crypter(idClient),
						   FenetreAccueil.getInstance().getPassword());
				instance.setAutoCommit(false);

			} catch (final Exception e) {
				e.printStackTrace();
			}
		return instance;
	}
	
	public static Connection getAdminConnection() throws SQLException{
		if (instance == null)
			try {
				ipServeur = "127.0.0.1";
				Class.forName("oracle.jdbc.driver.OracleDriver");

				instance = DriverManager.getConnection("jdbc:oracle:thin:@//" + ipServeur + ":1521/xe",
						   "U0",
						   "userir");
				instance.setAutoCommit(false);

			} catch (final Exception e) {
				e.printStackTrace();
			}
		return instance;
	}
	
	public static void terminerConnexion(){
		instance = null;
	}
}
